package com.stlm2.dems.card.service;

import com.stlm2.core.common.page.PageView;
import com.stlm2.dems.card.dao.BankDao;
import com.stlm2.dems.card.entity.Bank;
import com.stlm2.dems.user.dao.AccountDao;
import com.stlm2.dems.dao.UserDao;
import com.stlm2.dems.user.entity.Account;
import com.stlm2.dems.entity.User;
import com.stlm2.util.codecontent.CodeContent;
import org.apache.commons.lang.math.NumberUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;

import com.stlm2.dems.card.entity.Card;
import com.stlm2.dems.card.dao.CardDao;
import com.stlm2.core.base.BaseDao;
import com.stlm2.core.base.impl.BaseServiceImpl;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;

import java.util.*;

@Service("cardService")
@Transactional(rollbackForClassName={"java.lang.Exception"}, propagation = Propagation.REQUIRED)
public class CardService extends BaseServiceImpl<Card> {

	@Resource
	private CardDao cardDao;
    @Resource
	private UserDao userDao;
    @Resource
    private BankDao bankDao;
	@Resource
	private AccountDao accountDao;

	@Override
	protected BaseDao <Card> getDao() {
		return cardDao;
	}

	public HashMap<String,Object> addCard(String token,String bankId,String kaihuhang,String accountName,String cardNum){
		HashMap<String,Object> map=new HashMap<String, Object>();
//		try {
//			kaihuhang = new String (kaihuhang.getBytes("iso8859-1"), "UTF-8");
//			accountName = new String (accountName.getBytes("iso8859-1"), "UTF-8");
//		} catch (Exception ex) {
//			ex.printStackTrace();
//		}
		User user = userDao.getByToken(token);
		if (user == null) {
			map.put("code",-1);
			map.put("msg","您的登录已经过期，请重新登录");
		}
		if(!NumberUtils.isDigits(bankId)){
			map.put("code",0);
			map.put("msg","请选择银行");
			return map;
		}
		if (StringUtils.isEmpty(kaihuhang)) {
			map.put("code",0);
			map.put("msg","请填写开户支行");
			return map;

		}

		if (StringUtils.isEmpty(cardNum)) {
			map.put("code",0);
			map.put("msg","请填写银行卡号");
			return map;

		}
		if(cardNum.length() < 10 || cardNum.length() > 25) {
			map.put("code",0);
			map.put("msg","请填写正确的银行卡号");
			return  map;
		}
		if(StringUtils.isEmpty(accountName)){
			map.put("code",0);
			map.put("msg","请填写开户者姓名");
			return map;

		}
		Card cardDefault=cardDao.getByUserIdDefault(user.getId());
		Card  card=new Card();
		card.setAccountName(accountName);
		card.setBankId(NumberUtils.toInt(bankId));
		card.setKaihuhang(kaihuhang);
		card.setCreateTime(new Date());
		card.setCreateUserId(user.getId());
		card.setCardNum(cardNum);
		card.setState(true);
		card.setAppoint(true);
		if(cardDefault!=null ){
			cardDefault.setAppoint(false);
			cardDao.modify(cardDefault);
		}
		cardDao.add(card);
		map.put("code",1);
		map.put("msg","success");
		return map;


	}

	public HashMap<String,Object> updateCard(String token,String bankId,String kaihuhang,String accountName,String cardNum,String cardId){
		HashMap<String,Object> map=new HashMap<String, Object>();
//		try {
//			kaihuhang = new String (kaihuhang.getBytes("iso8859-1"), "UTF-8");
//			accountName = new String (accountName.getBytes("iso8859-1"), "UTF-8");
//		} catch (Exception ex) {
//			ex.printStackTrace();
//		}
		User user = userDao.getByToken(token);
		if (user == null) {
			map.put("code",-1);
			map.put("msg","您的登录已经过期，请重新登录");
		}
		if(!NumberUtils.isDigits(cardId)){
			map.put("code",0);
			map.put("msg","请选择银行卡");
			return map;
		}
		if(!NumberUtils.isDigits(bankId)){
			map.put("code",0);
			map.put("msg","请选择银行类型");
			return map;
		}
		if (StringUtils.isEmpty(kaihuhang)) {
			map.put("code",0);
			map.put("msg","请填写开户支行");
			return map;

		}
		if(StringUtils.isEmpty(accountName)){
			map.put("code",0);
			map.put("msg","请填写开户者姓名");
			return map;

		}
		if (StringUtils.isEmpty(cardNum)) {
			map.put("code",0);
			map.put("msg","请填写银行卡号");
			return map;

		}
		if(cardNum.length() < 10 || cardNum.length() > 25) {
			map.put("code",0);
			map.put("msg","请填写正确的银行卡号");
			return  map;
		}
		Card card=cardDao.getById(NumberUtils.toInt(cardId));
		if(card==null) {
			map.put("code",0);
			map.put("msg","未找到要编辑的银行卡");
			return  map;

		}else {

            Card cardDefault=cardDao.getByUserIdDefault(user.getId());
            if(cardDefault!=null &&cardDefault.getId()!=card.getId()){
                cardDefault.setAppoint(false);
                cardDao.modify(cardDefault);
            }
			card.setAccountName(accountName);
			card.setBankId(NumberUtils.toInt(bankId));
			card.setKaihuhang(kaihuhang);
			card.setCreateTime(new Date());
			card.setCreateUserId(user.getId());
			card.setCardNum(cardNum);
			card.setState(true);
			card.setAppoint(true);
			cardDao.modify(card);
		}
		map.put("code",1);
		map.put("msg","success");
		return map;

	}

	//获取用户银行卡 第一版用户只能绑定一张银行卡
	public String getCard(String token){
		ModelMap modelMap=new ModelMap();
		User user=userDao.getByToken(token);
		if(user==null){
			return CodeContent.getModelByCode(-1,"",null);
		}

		Card card=cardDao.getByUserId(user.getId());

		if(card!=null){
			return CodeContent.getModelByCode(1,"",buildModel(card));
		}

		return CodeContent.getModelByCode(0,"请添加银行卡" ,null);

	}
    //获取用户银行卡 列表  修改用户可以绑定多张银行卡
	public String getCardList(String token,Integer pageNu){
		ModelMap modelMap=new ModelMap();
		User user=userDao.getByToken(token);
		if(user==null){
			return CodeContent.getModelByCode(-1,"",null);
		}
		if(pageNu==null||pageNu<1){
			return CodeContent.getModelByCode(0,"请提供页数",modelMap);
		}
		Account account=accountDao.getByUserId(user.getId());
		if(account==null){
			return CodeContent.getModelByCode(0,"用户账户未找到",modelMap);
		}
		Card card=new Card();
		card.setCreateUserId(user.getId());
		modelMap.put("accountMoney",account.getAccountMoney());
		PageView pageView=cardDao.queryPageView(pageNu,10,card);
		if(pageView!=null){
			modelMap.put("cardList", convert_sale(pageView.getRecords()));
			modelMap.put("recordsTotal", pageView.getRowCount());
			modelMap.put("totalPage", pageView.getPageCount());
			return CodeContent.getModelByCode(1,"",modelMap);
		}


		return CodeContent.getModelByCode(0,"请添加银行卡" ,null);

	}

    //指定 某一张 银行卡 为默认银行卡
	public String updateCardDefault(String token, String cardId){

		User user = userDao.getByToken(token);
		if (user == null) {
			return CodeContent.getModelByCode(-1,"",null);
		}
		if(!NumberUtils.isDigits(cardId)){

			return CodeContent.getModelByCode(0,"请选择默认的银行卡",null);
		}

		Card  card=cardDao.getById(NumberUtils.toInt(cardId));
		Card cardDefault=cardDao.getByUserIdDefault(user.getId());
		if(card!=null) {
			if(card.getCreateUserId()==user.getId()){
				card.setAppoint(true);
			}else {
				return CodeContent.getModelByCode(0,"请传入自己绑定的银行卡",null);
			}

		}else {
			return CodeContent.getModelByCode(0,"请指定自己绑定的银行卡",null);
		}
		if(cardDefault!=null &&cardDefault.getId()!=card.getId() ){
			cardDefault.setAppoint(false);
			cardDao.modify(cardDefault);
		}


		cardDao.modify(card);
		return CodeContent.getModelByCode(1,"",null);

	}

	public List<ModelMap> convert_sale(List<Card> cardList) {
		List<ModelMap> list = new ArrayList<ModelMap>();
		if (cardList != null && cardList.size() > 0) {
			for (Card card : cardList) {
				ModelMap map = buildModel(card);
				list.add(map);
			}
		}

		return list;
	}

	public ModelMap buildModel_sample(Card card){
		ModelMap model = new ModelMap();
		if(card != null){
			model.put("accountName", org.apache.commons.lang.StringUtils.isNotEmpty(card.getAccountName()) ? card.getAccountName().trim() : "");
			model.put("cardNum", org.apache.commons.lang.StringUtils.isNotEmpty(card.getCardNum()) ? card.getCardNum().trim() : "");
			model.put("bankId", card.getBankId()!= null ? card.getBankId() : "");
			String bankImg=null;
			String bankPicture=null;
			if(card.getBankId()!=null){
			   Bank	bank=bankDao.getById(card.getBankId());
				bankImg=bank.getImg();
				bankPicture=bank.getPicture();
			}
			User user=userDao.getById(card.getCreateUserId());
			String userKey="";
			if(user!=null){
				userKey=user.getUserKey();
			}
			model.put("userKey",userKey);
			model.put("bankImg",bankImg!=null?bankImg:"");
			model.put("bankPicture",bankPicture!=null?bankPicture:"");
			model.put("id", card.getId() != null ? card.getId() : "");
			model.put("state", card.getState() != null ? card.getState() : false);
            model.put("isDefault",card.getAppoint()!=null?card.getAppoint():false);
		}
		return model;
	}


	public ModelMap buildModel(Card card){
		ModelMap model = new ModelMap();
		if(card != null){
			model.put("kaihuhang", org.apache.commons.lang.StringUtils.isNotEmpty(card.getKaihuhang()) ? card.getKaihuhang().trim() : "");
			model.put("accountName", org.apache.commons.lang.StringUtils.isNotEmpty(card.getAccountName()) ? card.getAccountName().trim() : "");
			if(card.getCardNum()!=null){
				model.put("cardNum",card.getCardNum());
				model.put("cardNumShort",card.getCardNum().substring(card.getCardNum().length()-4));
			}else {
				model.put("cardNumShort","");
				model.put("cardNum","");
			}
			model.put("bankId", card.getBankId()!= null ? card.getBankId() : "");
			String bankName=null;
			String bankImg=null;
			String bankPicture=null;
			if(card.getBankId()!=null){
				Bank	bank=bankDao.getById(card.getBankId());
				bankImg=bank.getImg();
				bankPicture=bank.getPicture();
				bankName=bank.getName();
			}
			User user=userDao.getById(card.getCreateUserId());
			String userKey="";
			if(user!=null){
				userKey=user.getUserKey();
			}
			model.put("userKey",userKey);
			model.put("bankImg",bankImg!=null?bankImg:"");
			model.put("bankPicture",bankPicture!=null?bankPicture:"");
			model.put("bank",bankName!=null?bankName:"");
			model.put("id", card.getId() != null ? card.getId() : "");
			model.put("state", card.getState() != null ? card.getState() : false);
			model.put("isDefault",card.getAppoint()!=null?card.getAppoint():false);
		}
		return model;
	}

	public  String employCard(String token){
		User user=userDao.getByToken(token);
		ModelMap model = new ModelMap();
		if(user==null){
			return CodeContent.getModelByCode(-1,"",null);
		}
		Card card=cardDao.getByUserId(user.getId());
		if(card!=null){
			Account account=accountDao.getByUserId(user.getId());
			model.put("accountKey", account.getAccountKey());
			model.put("accountMoney", account.getAccountMoney());
			model.put("accountName", org.apache.commons.lang.StringUtils.isNotEmpty(card.getAccountName()) ? card.getAccountName().trim() : "");
			model.put("bankId", card.getBankId()!= null ? card.getBankId() : "");
			if(card.getCardNum()!=null){
				model.put("cardNumShort",card.getCardNum().substring(card.getCardNum().length()-4));
				model.put("cardNum",card.getCardNum());
			}else {
				model.put("cardNumShort","");
				model.put("cardNum","");
			}
			Bank bank=new Bank();
			if(card.getBankId()!=null){
				bank=bankDao.getById(card.getBankId());
			}
			model.put("bankName",bank.getName());
			model.put("bankImg",bank.getImg());
			model.put("kaihuhang",card.getKaihuhang());
			model.put("cardId", card.getId() != null ? card.getId() : "");
			model.put("state", card.getState() != null ? card.getState() : false);
			return CodeContent.getModelByCode(1,"" ,model);
		}
		return CodeContent.getModelByCode(0,"请添加银行卡" ,model);

	}

	public String getOneCard(String token,Integer cardId){
		ModelMap modelMap=new ModelMap();
		User user=userDao.getByToken(token);
		if(user==null){
			return CodeContent.getModelByCode(-1,"",null);
		}
		if(cardId==null||cardId<1){
			return CodeContent.getModelByCode(0,"请提用户银行卡id",modelMap);
		}
		Card card=cardDao.getById(cardId);

		if(card!=null){
			return CodeContent.getModelByCode(1,"",buildModel(card));
		}
		return CodeContent.getModelByCode(0,"请添加银行卡" ,null);

	}
    //用户解绑银行卡
	public String unbindOneCard(String token,Integer cardId){
		ModelMap modelMap=new ModelMap();
		User user=userDao.getByToken(token);
		if(user==null){
			return CodeContent.getModelByCode(-1,"",null);
		}
		if(cardId==null||cardId<1){
			return CodeContent.getModelByCode(0,"请提用户银行卡id",modelMap);
		}
		Card card=cardDao.getById(cardId);
		if(card==null){
			return CodeContent.getModelByCode(1,"解绑成功！",modelMap);
		}
		card.setState(false);
		cardDao.modify(card);
		return CodeContent.getModelByCode(1,"解绑成功！" ,modelMap);

	}
}